/**
 * 许可证管理路由
 *
 * Created by snowingsea on 2020/02/24.
 */
const fs = require('fs-extra');
const path = require('path');
// const multer = require('multer');
const JSZip = require('jszip');
const middleware = require('./../middleware');
const utility = require('./../../models/utility');
const PhoenixError = require('./../../models/phoenix-error');
// const cacheUtil = require('../../cacheUtil');
const uploadProgress = require('../middleware/upload-progress');

/**
 * 上传测试报告模板
 * @param req
 * @param res
 * @param next
 * @returns {Promise}
 */
function uploadReportTemplate(req, res, next) {
  const { file } = req;
  fs.readFile(file.path)
    .then((buf) => {
      const zip = new JSZip(buf);
      return zip;
    })
    .then(async (zip) => {
      if (!zip.files['index.js']) {
        throw new PhoenixError('invalid request', 'index.js not found');
      }
      if (!zip.files['template.info.json']) {
        throw new PhoenixError('invalid request', 'template.info not found');
      }
      return JSON.parse(zip.files['template.info.json'].asText());
    })
    .then((templateInfo) => {
      if (!templateInfo || !templateInfo.reportFormats || Object.keys(templateInfo.reportFormats).length === 0) {
        throw new PhoenixError('file format error', 'import template file format error');
      }
      // 区分模版类型
      let templateType = 'enabled-report';
      if (templateInfo.reportFormats.staticAnalyzeByFiles || templateInfo.reportFormats.staticAnalyzeByRules) {
        templateType = 'enabled-analyze-report';
      }
      const destPath = path.join(__dirname, '..', '..', 'models', 'export', 'report', templateType);
      fs.emptyDir(destPath)
        .then(() => utility.uncompress(file.path, destPath))
        .then(() => fs.remove(file.path))
        .then(() => {
          res.status(204).json();
        });
    })
    .catch((err) => {
      next(new PhoenixError(err));
    });
}

/**
 * Export model definition object.
 */
module.exports = (app, prefix) => {
  const reportTemplateURL = `${prefix}/report-template.json`;
  const upload = uploadProgress;

  app.post(reportTemplateURL, middleware.user.requireTokenUnexpired);
  app.post(reportTemplateURL, middleware.user.requireAvailable);
  app.post(reportTemplateURL, middleware.user.requireAdministrator);
  app.post(reportTemplateURL, upload.single('template'));
  app.post(reportTemplateURL, uploadReportTemplate);
};
